<template>
  <div class="common-choose-dialog-wrap">
    <span
      class="label"
      @click="showDialog"
      v-if="!selectReports.length"
      :style="{ '--theme-color': systemInfo.theme }"
      >请选择</span
    >

    <div class="name-list" v-else @click="showDialog">
      <el-tag
        type="success"
        v-for="(item, index) in selectReports"
        :key="index"
        closable
        @close="delUser(index)"
      >
        {{ item }}
      </el-tag>
      <el-tag type="success" v-if="tempData.length > 5"
        >+{{ tempData.length - 5 }}</el-tag
      >
    </div>

    <common-choose-dialog
      ref="ChooseDialog"
      multiple
      :max="max"
      :unit="'个'"
      title="报告"
      width="50%"
      @submitForm="submitForm"
    >
      <!--tab标签页-->
      <common-tabs slot="tabs" v-model="activeName" @tab-click="changeTabs">
        <el-tab-pane label="全部列表" name="unselected"></el-tab-pane>
        <el-tab-pane label="已选择列表" name="selected"></el-tab-pane>
      </common-tabs>
      <!--全部列表-->
      <template v-if="activeName === 'unselected'">
        <common-search slot="search" @search="handleQuery" @reset="resetQuery">
          <el-form
            @submit.native.prevent
            :model="queryForm"
            ref="queryForm"
            :inline="true"
            label-width="70px"
          >
            <el-form-item label="报告名称">
              <common-input
                v-model="queryForm.name"
                clearable
                @enter="handleQuery"
              />
            </el-form-item>
          </el-form>
        </common-search>

        <common-table
          v-loading="listLoading"
          slot="content"
          ref="unSelectList"
          :data="allList"
          isSetRowKey
          :row-key="'name'"
          @select="selectionRow"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :reserve-selection="true"
          >
          </el-table-column>
          <el-table-column
            label="报告名称"
            align="left"
            prop="name"
            show-overflow-tooltip
          />
          <el-table-column
            label="描述"
            align="left"
            prop="description"
            show-overflow-tooltip
          />
          <el-table-column
            label="创建时间"
            align="left"
            width="180"
            prop="createTime"
          />
          <el-table-column label="操作" align="left" width="50px">
            <template slot-scope="scope">
              <el-button type="text" @click="handlePreview(scope.row)"
                >预览
              </el-button>
            </template>
          </el-table-column>
        </common-table>

        <pagination
          slot="pagination"
          v-show="total > 0"
          :total="total"
          :page.sync="queryForm.pageNum"
          :limit.sync="queryForm.pageSize"
          @pagination="handleList"
        />
      </template>

      <!--已选择-->
      <template v-else>
        <div slot="button">
          <el-button
            type="danger"
            icon="el-icon-delete"
            plain
            :disabled="!selectedDeleteValue.length"
            @click="handleDelete"
            >批量删除
          </el-button>
          <span style="margin-left: 24px"
            >总数量：{{ selectedData.length }}个</span
          >
        </div>

        <common-table
          slot="content"
          v-loading="selectListLoading"
          ref="selectList"
          :data="selectedData"
          @selection-change="handleSelectForDel"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="报告名称"
            align="left"
            prop="name"
            show-overflow-tooltip
          />
          <el-table-column
            label="描述"
            align="left"
            prop="description"
            show-overflow-tooltip
          />
          <el-table-column
            label="创建时间"
            align="left"
            width="180"
            prop="createTime"
          />
          <el-table-column label="操作" align="left" width="50">
            <template slot-scope="scope">
              <el-button type="text" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </common-table>
      </template>
    </common-choose-dialog>

    <report-preview ref="reportPreview"></report-preview>
  </div>
</template>

<script>
import HandleChooseDialog from "@/mixins/modules/HandleChooseDialog";
import ReportPreview from "./reportPreview";
import {
  reportList,
  getSelectedReports,
} from "@/api/screenConfig/subscribe/index";
import { _deepClone } from "@/utils";
import { mapGetters } from "vuex";

export default {
  name: "chooseDialog",
  components: {
    ReportPreview,
  },
  mixins: [HandleChooseDialog],
  props: {
    jobReports: {
      type: Array,
      default: () => [],
    },
    jobReportNames: {
      type: Array,
      default: () => [],
    },
    jobId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      activeName: "unselected",
      treeLoading: false,
      treeData: [],
      treeProp: {},
      allList: [],
      currentNodeKey: "",
      queryForm: {
        name: "",
        pageNum: 1,
        pageSize: 10,
        sourceType: "report_center",
      },
      selectListLoading: false, //已选择列表loading
      selectedData: [], //已选择列表
      selectedDeleteValue: "", //已选择列表中选中的数据
      selectReports: [], //用于展示选择的报告
      tempData: [],
      max: 10,
      key: "name",
    };
  },
  computed: {
    ...mapGetters(["systemInfo"]),
  },
  watch: {
    jobId: {
      handler: function (val) {
        if (val && !this.selectedData.length) {
          this.handleSelectedList();
        }
      },
      deep: true,
      immediate: true,
    },
    tempData: {
      handler: function (val) {
        this.setSelectNames();
      },
      deep: true,
    },
    allList: {
      handler: function (val) {
        if (val.length) {
          this.changeTabs();
        }
      },
      deep: true,
    },
    selectedData: {
      handler: function (val) {
        if (val.length) {
          this.changeTabs();
        }
      },
      deep: true,
    },
  },
  methods: {
    showDialog() {
      this.$refs.ChooseDialog.show();
      this.selectedData = _deepClone(this.tempData);
      this.queryForm = {
        name: "",
        pageNum: 1,
        pageSize: 10,
        sourceType: "report_center",
      };
      this.handleList();
    },

    //预览
    handlePreview(row) {
      this.$refs.reportPreview.show(row);
    },
    //切换分页
    changeTabs() {
      if (this.activeName === "unselected") {
        this.changeRowSelection();
      }
    },
    //弹窗提交事件
    submit() {
      if (this.selectedData.length > 10) {
        this.isClosed = false;
        return this.$GlobalErrorConfirm(
          "添加失败",
          `最多只能选择${this.max}个报告！`
        );
      } else {
        this.isClosed = true;
        this.tempData = _deepClone(this.selectedData);
        this.$emit("getSelectData", this.tempData);
      }
    },
    //展示选中
    setSelectNames() {
      if (this.tempData.length) {
        this.selectReports =
          this.tempData.length > 4
            ? this.tempData.map((item) => item.name).slice(0, 5)
            : this.tempData.map((item) => item.name);
      } else {
        this.selectReports = [];
      }
    },
    //重置筛选条件
    resetForm() {
      this.queryForm.name = "";
    },
    //展示中删除人员
    delUser(index) {
      this.tempData.splice(index, 1);
      this.$emit("getSelectData", this.tempData);
    },

    /**
     * 获取全部列表
     * @returns {Promise<any>}
     */
    getList() {
      return new Promise((resolve, reject) => {
        reportList({ ...this.queryForm, classType: 0 }).then((res) => {
          if (res && res.code === 200) {
            let list = res.rows;
            let total = res.total;
            resolve({ list, total });
          } else {
            this.allList = [];
            this.total = 0;
          }
        });
      });
    },

    /**
     * 获取已选择报告列表
     * @returns {Promise<any>}
     */
    getSelectedList() {
      return new Promise((resolve, reject) => {
        getSelectedReports({
          jobId: this.jobId,
          classType: 0,
          sourceType: "report_center",
        }).then((res) => {
          if (res && res.code === 200) {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
  },
  mounted() {},
};
</script>

<style scoped lang="scss">
.common-choose-dialog-wrap {
  .label {
    font-size: 14px;
    color: var(--theme-color);
    cursor: pointer;
  }

  .name-list {
    width: fit-content;

    .el-tag {
      margin-right: 4px;
      cursor: pointer;
    }
  }
}
</style>
